
import {
  Form,
  FormItem,
  Input,
  Select,
  Option,
  Card,
  Button,
  Cascader,
  Collapse,
  CollapseItem,
  Popconfirm
} from 'element-ui'
import { mapGetters } from 'vuex'
import { generateNanoid } from '@utils/nanoid'

// import { useModal } from '@/visual-editor/hooks/useModal'
import { cloneDeep } from 'lodash'

/**
 * @description 创建一个空的动作处理对象
 */
const createEmptyActionHandle = () => ({
  key: generateNanoid(),
  name: '',
  link: []
})

/**
 * @description 新增一个空的事件
 */
const createEmptyAction = () => ({
  key: generateNanoid(),
  name: '',
  event: '',
  handle: [createEmptyActionHandle()]
})

export const EventAction = ({
    name: 'EventAction',
    data() {
        return {
            activeNames: [],
            ruleForm: createEmptyAction()
        }
    },
    computed: {
        ...mapGetters('editor', ['focusBlock']),
        isEdit({focusBlock}) {
            return focusBlock.actions?.some((item) => item.key === this.ruleForm.key)
        },
    },
    mounted() {
        this.ruleFormRef = ''
    },
    methods: {
        addActionItem() {
            this.ruleForm = createEmptyAction()
            // this.showOperateModal()
        },
        deleteActionItem(index) {
            // currentBlock.value.actions.splice(index, 1)
        },
        showEditActionModal(action) {
            // this.ruleForm = cloneDeep(action)
            // this.showOperateModal()
        },
        getActionPath(link) {
            const result = []
            link.reduce((prev, curr) => {
              const target = prev?.find((item) => item.value == curr)
              result.push(`${target?.label}`)
              return target?.children
            }, this.actionOptions)
            return result.join(' => ')
        },
    },
    render(h) {
        return (
            <div>
              <Button
                onClick={this.addActionItem}
                // disabled={!this.currentBlock.actions}
                type={'primary'}
                size={'mini'}
              >
                添加事件
              </Button>
      
              {this.focusBlock?.actions?.map((actionItem, index) => (
                <Card
                  key={index}
                  class={'mt-10px'}
                  v-slots={{
                    header: () => (
                      <div class={'flex justify-between'}>
                        {actionItem.name}
                        <div>
                          <Popconfirm
                            title={'确定要删除该事件吗？'}
                            onConfirm={() => this.deleteActionItem(index)}
                          >
                            {{
                              reference: () => (
                                <Button type={'danger'} size={'mini'}>
                                  删除
                                </Button>
                              )
                            }}
                          </Popconfirm>
                          <Button
                            onClick={() => this.showEditActionModal(actionItem)}
                            type={'primary'}
                            size={'mini'}
                          >
                            编辑
                          </Button>
                        </div>
                      </div>
                    )
                  }}
                >
                  <Collapse v-model={this.activeNames}>
                    {actionItem.handle.map((item, index) => (
                      <CollapseItem title={`${index + 1}. ${item.name}`} key={item.key} name={item.key}>
                        {{
                          default: () => <div>动作路径：{this.getActionPath(item.link)}</div>
                        }}
                      </CollapseItem>
                    ))}
                  </Collapse>
                </Card>
              ))}
            </div>
          )
    },
//   setup() {
//     const { currentBlock, currentPage, jsonData } = useVisualData()
//     const isEdit = computed(() =>
//       currentBlock.value.actions?.some((item) => item.key === state.ruleForm.key)
//     )
//     const ruleFormRef = ''

//     const state = reactive<IState>({
//       activeNames: [],
//       ruleForm: createEmptyAction()
//     })

//     const actionOptions = computed(() => [
//       {
//         label: '全局',
//         value: 'global',
//         children: Object.keys(jsonData.actions).map((actionKey) => {
//           const item = cloneDeep(jsonData.actions[actionKey])
//           item.value = actionKey
//           item.label = item.name
//           const arrKey = Object.keys(item).find((key) => Array.isArray(item[key]))
//           item.children = (item[arrKey] || []).map((item: any) => {
//             item.label = item.name
//             item.value = item.key
//             return item
//           })
//           return item
//         })
//       },
//       {
//         label: '组件',
//         value: 'component',
//         children: cloneDeep(currentPage.value.blocks)
//           .filter((item) => item.actions?.length)
//           .map((item) => {
//             item.value = item._vid
//             item.label = item.label
//             item.children = (item.actions || []).map((item: any) => {
//               item.label = item.name
//               item.value = item.key
//               return item
//             })
//             return item
//           })
//       }
//     ])
//     const showOperateModal = () => {
//       const operateType = isEdit.value ? '编辑' : '新增'
//       useModal({
//         title: `${operateType}动作`,
//         props: { width: 600 },
//         content: () => (
//           <Form model={state.ruleForm} ref={ruleFormRef} label-width="100px" size={'mini'}>
//             <FormItem
//               label="事件"
//               prop={'event'}
//               rules={[{ required: true, message: '请选择事件', trigger: 'change' }]}
//             >
//               <Select v-model={state.ruleForm.event} class={'w-full'}>
//                 {currentBlock.value.events?.map((eventItem) => (
//                   <Option
//                     key={eventItem.value}
//                     label={eventItem.label}
//                     value={eventItem.value}
//                   ></Option>
//                 ))}
//               </Select>
//             </FormItem>
//             <FormItem
//               label="事件名称"
//               prop="name"
//               rules={[{ required: true, message: '请输入事件名称', trigger: 'change' }]}
//             >
//               <Input v-model={state.ruleForm.name} placeholder={'请输入事件名称'}></Input>
//             </FormItem>
//             {!state.ruleForm.handle?.length && (
//               <FormItem>
//                 <Button onClick={addActionHanleItem} type={'primary'} size={'mini'}>
//                   添加动作
//                 </Button>
//               </FormItem>
//             )}
//             {state.ruleForm.handle.map((handleItem, index) => (
//               <Card
//                 key={handleItem.key}
//                 shadow={'hover'}
//                 class={'mt-10px'}
//                 v-slots={{
//                   header: () => (
//                     <div class={'flex justify-between'}>
//                       <FormItem
//                         label="动作名称"
//                         prop={`handle.${index}.name`}
//                         rules={[{ required: true, message: '请输入动作名称', trigger: 'change' }]}
//                       >
//                         <Input v-model={handleItem.name} placeholder={'请输入动作名称'}></Input>
//                       </FormItem>
//                       <div>
//                         <Button
//                           onClick={() => deleteActionHandleItem(index)}
//                           type={'danger'}
//                           size={'mini'}
//                         >
//                           删除
//                         </Button>
//                         <Button onClick={addActionHanleItem} type={'primary'} size={'mini'}>
//                           添加
//                         </Button>
//                       </div>
//                     </div>
//                   )
//                 }}
//               >
//                 <FormItem
//                   label="触发的动作"
//                   prop={`handle.${index}.link`}
//                   rules={[{ required: true, message: '请选择你要触发的动作', trigger: 'change' }]}
//                 >
//                   <Cascader
//                     clearable={true}
//                     class={'w-full'}
//                     placeholder="请选择你要触发的动作"
//                     v-model={handleItem.link}
//                     options={actionOptions.value}
//                   ></Cascader>
//                 </FormItem>
//               </Card>
//             ))}
//           </Form>
//         ),
//         onConfirm: () => {
//           return new Promise((resolve, reject) => {
//             ruleFormRef.value?.validate((valid) => {
//               if (valid) {
//                 const index = currentBlock.value.actions.findIndex(
//                   (item) => item.key == state.ruleForm.key
//                 )
//                 if (index === -1) {
//                   currentBlock.value.actions.push(state.ruleForm)
//                 } else {
//                   currentBlock.value.actions.splice(index, 1, state.ruleForm)
//                 }
//                 state.ruleForm = createEmptyAction()
//                 resolve('submit!')
//               } else {
//                 reject()
//                 console.log('error submit!!')
//                 return false
//               }
//             })
//           })
//         },
//         onCancel: () => (state.ruleForm = createEmptyAction())
//       })
//     }

    
//   }
})
